import 'package:flutter/material.dart';
import 'package:flutter_basic_widgets/toast/toast_manager.dart';
import 'package:flutter_lang/lang_index.dart';
import 'package:route_manager/wx_navigator.dart';
// import 'package:wallet_home/model/wallet_list_model.dart';
import 'package:wallet_home/tools/theme_utils.dart';
import 'package:wallet_home/widget/coins_manager.dart';
import '../../image_r.dart';
import '../../module_config.dart';
import '../models/address_item_model.dart';
import '../plugin/dropdown_menu.dart';

class AddressNewPage extends StatefulWidget {
  final AddressItem addressItem;

  AddressNewPage({Key key, this.addressItem}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _AddressNewPageState();
}

class _AddressNewPageState extends State<AddressNewPage> {
  TextEditingController _nameEditController;
  TextEditingController _addressEditController;
  DropdownMenuController _dropdownMenuController = DropdownMenuController();
  FocusNode _nameFocus = FocusNode();
  FocusNode _addressFocus = FocusNode();
  bool isTapNameTF = false;
  GlobalKey _stackKey = GlobalKey();
  String _targetValue;
  List<SortCondition> _coinSortConditions;
  AddressItem _addressItem;

  bool isMenuOpen = false;

  @override
  void initState() {
    super.initState();
    _addressItem = widget.addressItem;

    _nameEditController = TextEditingController(text: _addressItem?.name ?? '');
    _addressEditController =
        TextEditingController(text: _addressItem?.address ?? '');

    _coinSortConditions = [];
    _preSortConditionList();
    // FocusScope.of(context).requestFocus();
  }

  _preSortConditionList() {
    List allCoinList = CoinManager().allCoinList;

      bool pRet = true;
      for (var i = 0; i < allCoinList.length; i++) {
        /// 默认新建时选中第一个币种显示选中
        if (_addressItem?.coinType == null) {
          if (i == 0) {
            _targetValue = allCoinList[i].title;

            /// 默认第一个为选中情况
            _coinSortConditions.add(
                SortCondition(name: allCoinList[i].title, isSelected: true));
            continue;
          }
        } else {
          /// 币种存在币种列表时
          if (_addressItem?.coinType == allCoinList[i].title) {
            _targetValue = _addressItem?.coinType;
            pRet = false;
            _coinSortConditions.add(
                SortCondition(name: allCoinList[i].title, isSelected: true));
            continue;
          }
        }
        _coinSortConditions
            .add(SortCondition(name: allCoinList[i].title, isSelected: false));
      }
      if (pRet && _addressItem?.coinType != null) {
        // 地址库列表存储的币种在总币种列表内并没有的币种情况处理
        _targetValue = _addressItem?.coinType;
        _coinSortConditions.insert(
            0,
            SortCondition(
                name: _addressItem?.coinType ?? '', isSelected: true));
      }
      setState(() {});

  }

  @override
  void dispose() {
    super.dispose();
    _nameEditController.dispose();
    _addressEditController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '${WXLang.$t("home_addNew_address", package: ModuleConfig.moduleName)}',
          style: TextStyle(
              color: ThemeUtils.getThemeColor(
                  context: context,
                  brightnessColor: Colors.grey[300],
                  darkColor: Colors.white)),
        ),
        brightness: Brightness.dark,
        centerTitle: true,
        leading: IconButton(
            icon: Icon(
              Icons.arrow_back,
              color: ThemeUtils.getThemeColor(
                  context: context,
                  brightnessColor: Colors.grey[300],
                  darkColor: Colors.white),
            ),
            onPressed: () {
              _dropdownMenuController.hide();
              WXNavigator.pop(context: context);
            }),
      ),
      body: Stack(
        key: _stackKey,
        children: <Widget>[
          SingleChildScrollView(
            child: Container(
              height: MediaQuery.of(context).size.height,
              child: Column(
                children: <Widget>[
                  DropDownHeader(
                    iconColor: ThemeUtils.getThemeColor(
                        context: context,
                        brightnessColor: Colors.grey[500],
                        darkColor: Colors.white60),
                    borderColor: Colors.transparent,
                    item: DropDownHeaderItem(_targetValue),
                    controller: _dropdownMenuController,
                    stackKey: _stackKey,
                    callback: (isOpen) {
                      isMenuOpen = isOpen;
                      print("===isOpen=====>$isOpen");
                      setState(() {});
                    },
                  ),
                  Expanded(
                      child: Column(
                    children: <Widget>[
                      nameWidget,
                      addressWidget,
                      bottomButtonWidget,
                    ],
                  )),
                ],
              ),
            ),
          ),
          DropDownMenu(
              controller: _dropdownMenuController,
              menu: DropdownMenuBuilder(
                  dropDownWidget:
                      _buildConditionListWidget(_coinSortConditions, (value) {
                    _targetValue = value.name;
                    Future.delayed(Duration(milliseconds: 200), () {
                      _dropdownMenuController.hide();
                    });
                    setState(() {});
                  }),
                  dropDownHeigth: 50.0 * _coinSortConditions.length))
        ],
      ),
    );
  }

  bool get _isEssentialEmpty {
    bool pRet = true;
    if (_addressEditController.text?.length != 0 &&
        _targetValue.length != 0 &&
        _nameEditController.text?.length != 0) {
      pRet = false;
    }
    return pRet;
  }

  get bottomButtonWidget => Padding(
        padding: EdgeInsets.symmetric(vertical: 30.0),
        child: FlatButton(
          onPressed: () {
            if (_isEssentialEmpty) {
              return;
            }
            print('保存按钮触发');
            bool isUpdate = widget.addressItem != null;
            AddressItem resultItem = AddressItem(
              _nameEditController.text,
              _targetValue,
              _addressEditController.text,
            );
            if (resultItem.islegal()) {
              /// 校验合法
              ToastManager.show(
                  "${WXLang.$t("home_addSuccess_address", package: ModuleConfig.moduleName)}",
                  duration: 1000);
              WXNavigator.pop(context: context, result: resultItem);
            } else {
              /// 非法给出提示
              if (isUpdate) {
                /// 更新非法
                ToastManager.show(
                    "${WXLang.$t("home_updateIllegal_address", package: ModuleConfig.moduleName)}",
                    duration: 1000);
              } else {
                /// 新增非法
                ToastManager.show(
                    "${WXLang.$t("home_addIllegal_address", package: ModuleConfig.moduleName)}",
                    duration: 1000);
              }
            }
          },
          child: Container(
            height: 38.0,
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(vertical: 0, horizontal: 15),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(3.0),
              color: _isEssentialEmpty
                  ? Colors.grey[350]
                  : Theme.of(context).primaryColor,
            ),
            child: Text(
              '${WXLang.$t("home_save_address", package: ModuleConfig.moduleName)}',
              style: TextStyle(color: Colors.white, fontSize: 16.0),
            ),
          ),
        ),
      );

  get addressWidget => Padding(
        padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
        child: Row(
          children: <Widget>[
            Container(
              child: Text(
                '${WXLang.$t("home_title_address", package: ModuleConfig.moduleName)}',
                style: TextStyle(
                    color: ThemeUtils.getThemeColor(
                        context: context,
                        brightnessColor: Colors.grey[600],
                        darkColor: Colors.white)),
              ),
            ),
            SizedBox(
              width: 20.0,
            ),
            Expanded(
              child: Container(
                height: 50.0,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(3.0),
                    border: Border.all(
                        color: ThemeUtils.getThemeColor(
                            context: context,
                            brightnessColor: Colors.grey[300],
                            darkColor: Colors.white),
                        width: 1)),
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                          focusNode: _addressFocus,
                          controller: _addressEditController,
                          onChanged: (value) {
                            setState(() {
                              _isEssentialEmpty;
                            });
                          },
                          onTap: () {},
                          decoration: InputDecoration(
                              contentPadding: EdgeInsets.fromLTRB(15, 5, 5, 5),
                              hintText:
                                  '${WXLang.$t("home_inputAddress_address", package: ModuleConfig.moduleName)}',
                              hintStyle: TextStyle(
                                  color: ThemeUtils.getThemeColor(
                                      context: context,
                                      brightnessColor: Colors.grey[300],
                                      darkColor: Colors.grey[500])),
                              border: InputBorder.none
                              // border: UnderlineInputBorder(
                              //     borderSide: BorderSide(
                              //   color: Colors.grey,
                              //   width: 1.0,
                              // )),
                              // enabledBorder: OutlineInputBorder(
                              //     borderSide: BorderSide(
                              //   color: Colors.grey,
                              //   width: 1.0,
                              // )),
                              // focusedBorder: OutlineInputBorder(
                              //     borderSide: BorderSide(
                              //   color: Colors.grey,
                              //   width: 1.0,
                              // )),
                              )),
                    ),
                    IconButton(
                        icon: Image.asset(ImageR.imagesQrcodeIcon,
                            width: 30,
                            height: 30,
                            color: ThemeUtils.getThemeColor(
                                context: context,
                                brightnessColor: Colors.grey[500],
                                darkColor: Colors.white70),
                            fit: BoxFit.fill,
                            package: ModuleConfig.moduleName),
                        onPressed: () {
                          print('扫描功能');
                          _addressFocus.unfocus();
                          _nameFocus.unfocus();

                          Future.delayed(Duration(milliseconds: 500), () async {
                            String qrcode = await WXNavigator.pushNamed(
                                routeName: "/qrcode_scan");
                            // 扫描结果不为空时，刷新结果
                            if (qrcode != null && qrcode.length != 0) {
                              _addressEditController.text = qrcode;
                              setState(() {
                                /// 再次判断其是否为空，更新保存按钮颜色
                                _isEssentialEmpty;
                              });
                            }
                          });
                        }),
                  ],
                ),
              ),
            ),
          ],
        ),
      );

  get nameWidget => Padding(
        padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(bottom: 10.0),
                  child: Text(
                    '${WXLang.$t("home_name_address", package: ModuleConfig.moduleName)}',
                    style: TextStyle(
                        color: ThemeUtils.getThemeColor(
                            context: context,
                            brightnessColor: Colors.grey[600],
                            darkColor: Colors.white)),
                  ),
                ),
              ],
            ),
            TextField(
                focusNode: _nameFocus,
                onEditingComplete: () {
                  _nameFocus.unfocus();
                  setState(() {
                    isTapNameTF = false;
                  });
                },
                controller: _nameEditController,
                onChanged: (value) {
                  setState(() {
                    _isEssentialEmpty;
                  });
                },
                onTap: () {
                  print('onTap-nameTF');
                  setState(() {
                    isTapNameTF = true;
                  });
                },
                decoration: InputDecoration(
                  suffixIcon: isTapNameTF
                      ? IconButton(
                          icon: Image.asset(
                            ImageR.imagesAddressCloseIcon,
                            package: ModuleConfig.moduleName,
                            color: ThemeUtils.getThemeColor(
                                context: context,
                                brightnessColor: Colors.grey[400],
                                darkColor: Colors.white),
                            height: 15,
                            width: 15,
                            fit: BoxFit.cover,
                          ),
                          onPressed: () {
                            print('删除当前输入内容');
                            _nameEditController.text = '';
                          })
                      : null,
                  contentPadding: EdgeInsets.fromLTRB(15, 5, 5, 5),
                  hintText:
                      '${WXLang.$t("home_inputName_address", package: ModuleConfig.moduleName)}',
                  hintStyle: TextStyle(
                      color: ThemeUtils.getThemeColor(
                          context: context,
                          brightnessColor: Colors.grey[300],
                          darkColor: Colors.grey[500])),
                  helperStyle: TextStyle(color: Colors.black, fontSize: 12.0),
                  suffixStyle: TextStyle(color: Colors.green),
                  border: OutlineInputBorder(
                      borderSide: BorderSide(
                    color: ThemeUtils.getThemeColor(
                        context: context,
                        brightnessColor: Colors.grey[300],
                        darkColor: Colors.white),
                    width: 1.0,
                  )),
                  enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                    color: ThemeUtils.getThemeColor(
                        context: context,
                        brightnessColor: Colors.grey[300],
                        darkColor: Colors.white),
                    width: 1.0,
                  )),
                  focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide(
                    color: ThemeUtils.getThemeColor(
                        context: context,
                        brightnessColor: Colors.grey[300],
                        darkColor: Colors.white),
                    width: 1.0,
                  )),
                )),
          ],
        ),
      );

  _buildConditionListWidget(
      List<SortCondition> items, void itemOnTap(SortCondition sortCondition)) {
    return Container(
      decoration: BoxDecoration(
          border: Border.all(
              color: ThemeUtils.getThemeColor(
                  context: context,
                  brightnessColor:
                      isMenuOpen ? Colors.grey[200] : Colors.transparent,
                  darkColor: isMenuOpen ? Colors.white54 : Colors.transparent),
              width: 0.5)),
      child: ListView.separated(
        shrinkWrap: true,
        scrollDirection: Axis.vertical,
        itemCount: items.length,
        separatorBuilder: (context, index) => Divider(
          height: 1.0,
        ),
        itemBuilder: (context, index) {
          SortCondition coinSortCondition = items[index];
          return GestureDetector(
            onTap: () {
              for (var value in items) {
                value.isSelected = false;
              }
              coinSortCondition.isSelected = true;
              itemOnTap(coinSortCondition);
            },
            child: Container(
              height: 50,
              color: ThemeUtils.getThemeColor(
                  context: context,
                  brightnessColor: Colors.white,
                  darkColor: Colors.grey[800]),
              child: Row(
                children: <Widget>[
                  SizedBox(
                    width: 16,
                  ),
                  Expanded(
                      child: Text(
                    coinSortCondition.name,
                    style: TextStyle(
                        color: ThemeUtils.getThemeColor(
                            context: context,
                            brightnessColor: coinSortCondition.isSelected
                                ? Theme.of(context).primaryColor
                                : Colors.black,
                            darkColor: coinSortCondition.isSelected
                                ? Theme.of(context).primaryColor
                                : Colors.white)
//                        color: coinSortCondition.isSelected
//                            ? Theme.of(context).primaryColor
//                            : Colors.black
                        ),
                  )),
                  coinSortCondition.isSelected
                      ? Icon(
                          Icons.check,
                          color: Theme.of(context).primaryColor,
                          size: 16,
                        )
                      : SizedBox(),
                  SizedBox(
                    width: 16,
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}
